package com.dahuilang.materialflow.controller;

import com.alibaba.excel.EasyExcel;
import com.dahuilang.materialflow.annotation.CrossOrigin;
import com.dahuilang.materialflow.pojo.User;
import com.dahuilang.materialflow.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/queryUsers")
    public List<User> queryUsers(){
        return userService.queryUsers().stream().filter(t->t.getId()>3).collect(Collectors.toList());
    }

    @GetMapping("/testRespExcel")
    public void testRespExcel(HttpServletResponse response){
        response.addHeader("Content-Disposition", "attachment;filename=" + "testExcel.xlsx");
        response.setContentType("application/vnd.ms-excel;charset=gb2312");
        try {
//            从HttpServletResponse中获取OutputStream输出流
            ServletOutputStream outputStream = response.getOutputStream();
            /*
             * EasyExcel 有多个不同的read方法，适用于多种需求
             * 这里调用EasyExcel中通过OutputStream流方式输出Excel的write方法
             * 它会返回一个ExcelWriterBuilder类型的返回值
             * ExcelWriterBuilde中有一个doWrite方法，会输出数据到设置的Sheet中
             */
            EasyExcel.write(outputStream, User.class).sheet("测试数据").doWrite(userService.queryUsers());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }





}
